<?php
/**
 * Created by PhpStorm.
 * User: ZZF
 * Date: 2017/12/8
 * Time: 14:42
 */

namespace app\home\model;
use think\Model;
class OrderModel extends Model{

    /**
     * @param $cart
     * @param $shipping_id
     * @param $user_id
     * @return array
     * 计算购物车物流价格
     */
    public function calculateShippingPrice($cart,$shipping_id,$user_id){
        $shipping_price = 0;
        $weight = 0;
        foreach($cart['cartList'] as $item){
            if($item['is_checked'] > 0){
                $weight += $item['goods_num'] * $item['weight'];
            }
        }
        $weight = ceil($weight/1000);
        if($weight < 1){
            return ['code'=>-1,'msg'=>'请求失败'];
        }
        //查询物流配送区域
        $areaIds = db('ShippingArea')->where(['shipping_id'=>$shipping_id])->value(['group_concat(id)']);
        if(!$areaIds){
            return ['code'=>-1,'msg'=>'不支持该配送方式'];
        }

        //根据默认地址计算
        $defaultAddress = db('UserAddress')->where(['user_id'=>$user_id,'is_default'=>1])->find();

        //查配送区域
        $where['shipping_area_id'] = ['in',$areaIds];
        $where['region_id'] = ['in',"{$defaultAddress['district']},{$defaultAddress['city']},{$defaultAddress['province']}"];
        if(!$areaId = db('ShippingAreaRegion')->where($where)->value('shipping_area_id')){
            //查默认中国
            $where['region_id'] = 1;
            if(!$areaId = db('ShippingAreaRegion')->where($where)->value('shipping_area_id')){
                return ['code'=>-1,'msg'=>'该商品在该地区暂不支持销售'];
            }
        }
        unset($where);

        //根据区域首重续重计算运费
        $shippingArea = db('ShippingArea')->where(['id'=>$areaId])->find();
        $shipping_price += $shippingArea['first_price'];
        if(($surplusWeight = $weight - 1) > 0){
            $shipping_price += $surplusWeight * $shippingArea['add_price'];
        }

        return ['code'=>1,'result'=>$shipping_price];

    }
}